package org.boulderfoodrescue.webapp.client.old.tests;

import java.util.HashMap;
import java.util.Map;

import org.boulderfoodrescue.webapp.test.TestCompleteEvent;
import org.boulderfoodrescue.webapp.test.TestCompleteHandler;
import org.boulderfoodrescue.webapp.test.TestManager;
import org.boulderfoodrescue.webapp.test.TestResult;
import org.boulderfoodrescue.webapp.test.TestStartEvent;
import org.boulderfoodrescue.webapp.test.TestStartedEvent;
import org.boulderfoodrescue.webapp.test.TestStartedHandler;
import org.boulderfoodrescue.webapp.test.Tests;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

public class TestsPanel extends Composite{

  private static TestsPanelUiBinder uiBinder = GWT
      .create(TestsPanelUiBinder.class);

  interface TestsPanelUiBinder extends UiBinder<Widget, TestsPanel> {
  }

  public TestsPanel() {
    initWidget(uiBinder.createAndBindUi(this));
    Tests.InitlizeTests();
    TestManager.get().addHandler(new TestStartedHandler(){
      @Override
      public void onTestStarted(String test_package) {
        onNewTestStarted(test_package);
      }
    }, TestStartedEvent.getType());
    
    TestManager.get().addHandler(new TestCompleteHandler(){
      @Override
      public void onTestComplete(TestResult result) {
        onNewTestComplete(result);
      }
    }, TestCompleteEvent.getType());
  }
  
  @UiField
  Button run_tests;
  @UiField
  TestsCellTable test_results;
  protected Map<String, TestResult> rowMap = new HashMap<String, TestResult>();
  
  @UiHandler ("run_tests")
  public void onRunTestsClick(ClickEvent e)
  {
    test_results.clearTable();
    rowMap.clear();
    TestManager.get().fireEvent(new TestStartEvent());
  }
  public void onNewTestStarted(String test_package){
    TestResult tr = new TestResult(test_package, null, null);
    rowMap.put(test_package, tr);
    test_results.addTestResult(tr);
  }
  public void onNewTestComplete(TestResult result){
    TestResult tr = rowMap.get(result.getTestPackage());
    if(tr != null){
      tr.setSuccess(result.getSuccess());
      tr.setTestMessage(result.getTestMessage());
    } else{
      System.out.println("Error: Null tr");
      result.getTestPackage();
    }
    test_results.redrawTable();
  }
  
}
